package com.gmcc.aiquality.common.online.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.gmcc.aiquality.common.core.annotation.MyRequestBody;
import com.gmcc.aiquality.common.core.constant.ErrorCodeEnum;
import com.gmcc.aiquality.common.core.object.ResponseResult;
import com.gmcc.aiquality.common.core.object.TokenData;
import com.gmcc.aiquality.common.core.util.MyCommonUtil;
import com.gmcc.aiquality.common.core.util.MyModelUtil;
import com.gmcc.aiquality.common.online.dto.OnlineApiGroupDto;
import com.gmcc.aiquality.common.online.model.OnlineApi;
import com.gmcc.aiquality.common.online.model.OnlineApiGroup;
import com.gmcc.aiquality.common.online.service.OnlineApiGroupService;
import com.gmcc.aiquality.common.online.service.OnlineApiService;
import com.gmcc.aiquality.common.online.vo.OnlineApiGroupVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 在线表单自定义API分组接口。
 *
 * @author 孙先生
 * @date 2025-10-23
 */
@Tag(name = "通用API分组接口")
@Slf4j
@RestController
@RequestMapping("${common-online.urlPrefix}/onlineApiGroup")
@ConditionalOnProperty(name = "common-online.operationEnabled", havingValue = "true")
public class OnlineApiGroupController {

    @Autowired
    private OnlineApiGroupService onlineApiGroupService;
    @Autowired
    private OnlineApiService onlineApiService;

    /**
     * 新增在线表单API分组数据。
     *
     * @param onlineApiGroupDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {"onlineApiGroupDto.groupId"})
    @SaCheckPermission("onlineApi.all")
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody OnlineApiGroupDto onlineApiGroupDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(onlineApiGroupDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        OnlineApiGroup onlineApiGroup = MyModelUtil.copyTo(onlineApiGroupDto, OnlineApiGroup.class);
        // 验证父Id的数据合法性
        OnlineApiGroup parentOne;
        if (ObjectUtil.isNotEmpty(onlineApiGroup.getParentId())) {
            parentOne = onlineApiGroupService.getById(onlineApiGroup.getParentId());
            if (parentOne == null) {
                errorMessage = "数据验证失败，关联的父节点并不存在，请刷新后重试！";
                return ResponseResult.error(ErrorCodeEnum.DATA_PARENT_ID_NOT_EXIST, errorMessage);
            }
        }
        onlineApiGroup = onlineApiGroupService.saveNew(onlineApiGroup);
        return ResponseResult.success(onlineApiGroup.getGroupId());
    }

    /**
     * 更新在线表单API分组数据。
     *
     * @param onlineApiGroupDto 更新对象。
     * @return 应答结果对象。
     */
    @SaCheckPermission("onlineApi.all")
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody OnlineApiGroupDto onlineApiGroupDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(onlineApiGroupDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        OnlineApiGroup onlineApiGroup = MyModelUtil.copyTo(onlineApiGroupDto, OnlineApiGroup.class);
        ResponseResult<OnlineApiGroup> verifyResult = this.doVerifyAndGet(onlineApiGroupDto.getGroupId());
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        OnlineApiGroup originalOnlineApiGroup = verifyResult.getData();
        // 验证父Id的数据合法性
        if (ObjectUtil.isNotEmpty(onlineApiGroup.getParentId())
                && ObjectUtil.notEqual(onlineApiGroup.getParentId(), originalOnlineApiGroup.getParentId())) {
            OnlineApiGroup parentOne = onlineApiGroupService.getById(onlineApiGroup.getParentId());
            if (parentOne == null) {
                // NOTE: 修改下面方括号中的话述
                errorMessage = "数据验证失败，关联的 [父节点] 并不存在，请刷新后重试！";
                return ResponseResult.error(ErrorCodeEnum.DATA_PARENT_ID_NOT_EXIST, errorMessage);
            }
        }
        if (!onlineApiGroupService.update(onlineApiGroup, originalOnlineApiGroup)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除在线表单API分组数据。
     *
     * @param groupId 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("onlineApi.all")
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long groupId) {
        return this.doDelete(groupId);
    }

    /**
     * 列出符合过滤条件的在线表单API分组列表。
     *
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("onlineApi.all")
    @PostMapping("/list")
    public ResponseResult<List<OnlineApiGroupVo>> list() {
        List<OnlineApiGroup> onlineApiGroupList = onlineApiGroupService.getOnlineApiGroupList(null, null);
        return ResponseResult.success(BeanUtil.copyToList(onlineApiGroupList, OnlineApiGroupVo.class));
    }

    /**
     * 查看指定在线表单API分组对象详情。
     *
     * @param groupId 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("onlineApi.all")
    @GetMapping("/view")
    public ResponseResult<OnlineApiGroupVo> view(@RequestParam Long groupId) {
        ResponseResult<OnlineApiGroup> verifyResult = this.doVerifyAndGet(groupId);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        OnlineApiGroupVo reportDatasetGroupVo = BeanUtil.toBean(verifyResult.getData(), OnlineApiGroupVo.class);
        return ResponseResult.success(reportDatasetGroupVo);
    }

    /**
     * 获取所有在线表单API分组数据和全部在线表单API数据。
     * 白名单接口。
     *
     * @return 应答数据结果。
     */
    @PostMapping("/listAll")
    public ResponseResult<JSONObject> listAll() {
        List<OnlineApiGroup> onlineApiGroupList = onlineApiGroupService.getOnlineApiGroupList(null, null);
        List<OnlineApi> onlineApiList = onlineApiService.getOnlineApiList(null);
        JSONObject resultData = new JSONObject();
        resultData.put("onlineApiGroupList", onlineApiGroupList);
        resultData.put("onlineApiList", onlineApiList);
        return ResponseResult.success(resultData);
    }

    private ResponseResult<Void> doDelete(Long groupId) {
        String errorMessage;
        // 验证关联Id的数据合法性
        ResponseResult<OnlineApiGroup> verifyResult = this.doVerifyAndGet(groupId);
        if (!verifyResult.isSuccess()) {
            return ResponseResult.errorFrom(verifyResult);
        }
        if (onlineApiGroupService.hasChildren(groupId)) {
            errorMessage = "数据验证失败，当前在线表单API分组存在子分组，请先删除下级分组！";
            return ResponseResult.error(ErrorCodeEnum.HAS_CHILDREN_DATA, errorMessage);
        }
        OnlineApi filter = new OnlineApi();
        filter.setGroupId(groupId);
        if (onlineApiService.getCountByFilter(filter) > 0) {
            errorMessage = "数据验证失败，当前在线表单API分组存在API数据，请先删除所属的API数据！";
            return ResponseResult.error(ErrorCodeEnum.HAS_CHILDREN_DATA, errorMessage);
        }
        if (!onlineApiGroupService.remove(groupId)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }

    private ResponseResult<OnlineApiGroup> doVerifyAndGet(Long groupId) {
        if (MyCommonUtil.existBlankArgument(groupId)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        OnlineApiGroup group = onlineApiGroupService.getById(groupId);
        if (group == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        if (!StrUtil.equals(group.getAppCode(), TokenData.takeFromRequest().getAppCode())) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, "数据验证失败，当前应用并不存在该数据集分组！");
        }
        return ResponseResult.success(group);
    }
}
